home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3000 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.4 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Fastest way to computer log(base2) of x?
  5. Date: Thu, 25 Jan 1996 13:24:26 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9601251224.AA06563@dxmint.cern.ch>
  8. References: <4e61iu$p6e@villa.fc.net> <4e6p7t$1n72@cymbal.aix.calpoly.edu>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. dstubbs@cymbal.aix.calpoly.edu (Dan Stubbs) writes:
  14.  
  15. >int  left_most_bit (int k) {
  16. >/*   
  17. > *   returns the position of the left most bit in k assuming that
  18. > *      k != 0 and 32 bit ints. The algorithm used is essentially a
  19. > *      binary search.
  20. > */
  21. >   int posn = 0, width = 16, mask = 0xffff0000;
  22. >
  23. >   while (width > 1) {
  24. >      if (k & mask) {
  25. >         width /= 2;
  26. >         mask <<= (posn + width);
  27. >         mask >>=  posn;
  28.           ^^^^^^^^^^^^^^
  29. >      }
  30. >      else {
  31. >         mask >>= width;
  32.           ^^^^^^^^^^^^^^
  33. Once again:  if the sign bit is set (and it is in this example) the
  34. result of this operation is IMPLEMENTATION-DEFINED.  The sign bit may
  35. be replicated in the "emptied" positions or they may be set to zero.
  36. Anybody who managed to read the first 49 pages of K&R2 _should_ know this.
  37.  
  38. Dan
  39. -- 
  40. Dan Pop
  41. CERN, CN Division
  42. Email: danpop@mail.cern.ch 
  43. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  44.